import urllib.request as ur
import urllib.parse as up
import json
#http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule
def fanyi():
    url = 'https://fanyi.baidu.com/v2transapi'
    headers = {
        'Accept':'*/*',
        'Connection':"keep-alive",
        'Content-Length':"167",
        'Cookie':"BAIDUID=22A5B2C1386536C1FFE1C5541FAB30B4:FG=1; BIDUPSID=BD5E197885EC8ACD2E80F04A2BF2D813; PSTM=1574333758; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1588829275,1588905576,1588920500,1588927293; REALTIME_TRANS_SWITCH=1; FANYI_WORD_SWITCH=1; HISTORY_SWITCH=1; SOUND_SPD_SWITCH=1; SOUND_PREFER_SWITCH=1; MCITY=-131%3A; BDUSS=UFvTmpZUktBb0pqSUc1TVpDVlQ3UnNvLWF-QmNEM1pzcFc5YXlTMnBMMldCRVZlRVFBQUFBJCQAAAAAAAAAAAEAAACMH0qUvsOw6bLFx-nJ7rDJAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJZ3HV6Wdx1eb; BDORZ=FFFB88E999055A3F8A630C64834BD6D0; yjs_js_security_passport=f80df94fe0d7b025cec6b4d85409f6b745745bbf_1588927959_js; __yjsv5_shitong=1.0_7_f1507fb6e92717232ce5549ba8ec53a81552_300_1588927958523_211.103.135.177_a14cd6de; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1588927860; BDRCVFR[Fc9oatPmwxn]=mk3SLVN4HKm; delPer=0; PSINO=1; H_PS_PSSID=1465_31325_21085",
        'Host':"fanyi.baidu.com",
        'X-Requested-With':"XMLHttpRequest",
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36'
    }
    data = {

        'from': 'zh',
        'to': 'en',
        'query': '百度翻译',
        'transtype': 'realtime',
        'simple_means_flag': '3',
        'sign': '773378.994867',
        'token': '5015c180fd37b79ac7734d873abacda2',
        'domain': 'common'
    }


    data = up.urlencode(data).encode('utf-8')

    res = ur.Request(url, headers=headers, data=data,method='POST')

    response = ur.urlopen(res).read().decode('utf-8')

    myjson = json.loads(response)

    print(myjson)
    print(myjson['dict_result']['netdata']['types'][0]['trans'])


if __name__ == '__main__':

        fanyi()